package com.shop.www.dao.Impl;

import com.shop.www.dao.CommodityDAO;
import com.shop.www.model.Commodity;
import com.shop.www.ssm.BasicDao;

import java.util.ArrayList;
import java.util.List;

import static java.util.stream.Collectors.toList;

public class CommodityDAOImpl extends BasicDao implements CommodityDAO {
    @Override
    public List<Commodity> getcommodity(String key,Integer state) {
        String sql = ("select * from Commodity where commodity_name like ? and state=?");
        List<Commodity> list1 = querymany(sql, Commodity.class,"%"+key+"%",state);
        String sql2 = ("SELECT s.* FROM commodity s INNER JOIN `user` c ON s.user_id = c.user_id WHERE c.user_name like ? and s.state=?");
        List<Commodity> list2 = querymany(sql2, Commodity.class,"%"+key+"%",state);
        List<Commodity> list =new ArrayList<Commodity>(list1);
        list.addAll(list2);
        List<Commodity> listAllDistinct = list.stream().distinct().collect(toList());
        return listAllDistinct;
    }

    @Override
    public Commodity getcommodityByID(Integer Commodity_ID) {
        String sql = ("select * from Commodity Where Commodity_ID = ?");
        return (Commodity) querysingle(sql,Commodity.class,Commodity_ID);
    }

    @Override
    public List<Commodity> getcommodityListbyseller(Integer user_ID,String state) {
        String sql = ("select * from Commodity where user_ID = ? and state like ?");
        List<Commodity> list = querymany(sql, Commodity.class,user_ID,state);
        return list;
    }

    @Override
    public void updatecommoditystate(Commodity commodity) {
        String sql =("update commodity set state = ? where Commodity_ID = ?");
        update(sql,commodity.getState(),commodity.getCommodity_ID());
    }

    @Override
    public void addcommodity(Commodity commodity) {
        String sql =("insert into `Commodity` values(0,?,?,?,?,?,?,?)");
        update(sql,commodity.getCommodity_IMG(), commodity.getCommodity_name(),
                commodity.getPrice(), commodity.getSaleCount(),
                commodity.getInventory(), commodity.getUser_ID(),
                commodity.getState());
    }

    @Override
    public void sellcommodity(Commodity commodity) {
        String sql =("update commodity set SaleCount =?,inventory=? where Commodity_ID = ?");
        update(sql,commodity.getSaleCount(),commodity.getInventory(),commodity.getCommodity_ID());
    }

    @Override
    public void updatecommodity(Commodity commodity) {
        String sql =("update commodity set commodity_IMG=?,commodity_name=?,price=?,inventory=? where Commodity_ID = ?");
        update(sql,commodity.getCommodity_IMG(),commodity.getCommodity_name(),commodity.getPrice(),commodity.getInventory(),commodity.getCommodity_ID());
    }

    @Override
    public void delcommodity(Integer Commodity_ID) {
        String sql = ("delete from commodity where commodity_ID = ?");
        update(sql,Commodity_ID);
    }

}
